package com.jxwifi.cloud.quickclean.assemble;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.AssembleTypeAdapter;
import com.jxwifi.cloud.quickclean.adapter.AutoPollAdapter;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.LocationGaoDe;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.AdvertBean;
import com.jxwifi.cloud.quickclean.bean.AdvertListBean;
import com.jxwifi.cloud.quickclean.bean.AssemRecordsBean;
import com.jxwifi.cloud.quickclean.bean.AssembleIndexBean;
import com.jxwifi.cloud.quickclean.bean.AssembleItemsBean;
import com.jxwifi.cloud.quickclean.bean.InfoBean;
import com.jxwifi.cloud.quickclean.bean.ParameterBean;
import com.jxwifi.cloud.quickclean.main.WebViewsActivity;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.popwindow.PopAssemTypeModle;
import com.jxwifi.cloud.quickclean.popwindow.PopAssembleJoin;
import com.jxwifi.cloud.quickclean.utils.GlideImageLoader;
import com.jxwifi.cloud.quickclean.utils.RouteManager;
import com.jxwifi.cloud.quickclean.utils.ScrollSpeedLinearLayoutManger;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;
import com.umeng.analytics.MobclickAgent;
import com.view.SuperSwipeRefreshLayout;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AssembleMainPresenter implements AssembleMainFilter{

    private String TAG = this.getClass().getSimpleName();
    private Context mContext;
    private AuzImpl mAuz;
    private AssembleMainView mView;
    private String area;
    private String city;
    private String province;
    private String mAddressid; //地址id

    private  AssembleIndexBean mAssembleIndex;//数据实体
    private ArrayList<String> list_images_path;
    private List<AdvertListBean> mListAdvert=new ArrayList<>();//广告集合
    private AssembleTypeAdapter mTypeAdapter;
    private AutoPollAdapter mAutoPollAdapter;
    private AssemRecordsBean mAssre;

    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    private int refreshCount = 0;
    private PopAssemTypeModle mMoble;
    private boolean isFilter = false;

    public AssembleMainPresenter(Context context,AssembleMainView view){
        this.mContext=context;
        mView=view;
        mAuz=new AuzImpl();
    }

    //用户信息
    public void getinfo() {
        Params params = new Params();
        params.add("customerCode", AccountMgr.getCode(mContext));
        mAuz.auzget(UrlPool.GET_INFO, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    InfoBean minfoBean = JSON.parseObject(data, InfoBean.class);
                    AccountMgr.putUser(mContext, minfoBean, true);

                    //如果地址为空获取当前位置信息,用于做首页的数据请求
                    if (minfoBean.getDefaultAddress() != null) {
                        if (minfoBean.getDefaultAddress().getArea() == null || "null".equals(minfoBean.getDefaultAddress().getCity())
                                || TextUtils.isEmpty(minfoBean.getDefaultAddress().getProvince())) {
                            area = LocationGaoDe.getArea();
                            city = LocationGaoDe.getCity();
                            province = LocationGaoDe.getProvince();
                        } else {
                            area = minfoBean.getDefaultAddress().getArea();
                            city = minfoBean.getDefaultAddress().getCity();
                            province = minfoBean.getDefaultAddress().getProvince();
                            mAddressid = minfoBean.getDefaultAddress().getId();
                        }
                    } else {
                        area = LocationGaoDe.getArea();
                        city = LocationGaoDe.getCity();
                        province = LocationGaoDe.getProvince();
                    }
                    initData();
                } else {
                    mView.oninfo();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });

    }

    public void initData(){
        Params params=new Params();
        params.add("area",area);
        params.add("city",city);
        params.add("limit","100");
        params.add("page","1");
        params.add("province",province);
        mAuz.auzpost(UrlPool.ASSEMBLE_INDEX, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                //AssembleIndexBean
                if (mListAdvert.size()>0){
                    mListAdvert.clear();
                }
                //Log.i(TAG,"initData ==> data = "+data);
                mAssembleIndex = JSON.parseObject(data, AssembleIndexBean.class);
                mListAdvert.addAll(mAssembleIndex.getAdvertList());
                initView();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void initView(){
        initBanner();
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);//调用下面这行代码可以实现布局横向排列
        mView.getAssembleType().setLayoutManager(layoutManager);
        mView.getAssembleType().setAdapter(mTypeAdapter = new AssembleTypeAdapter(R.layout.assemble_type_item));
        mTypeAdapter.openLoadAnimation();
        mTypeAdapter.openLoadAnimation(BaseQuickAdapter.FOOTER_VIEW);
        if (mAssembleIndex.getAssembles().size()>0){
            mAssembleIndex.getAssembles().get(0).setCheck(true);
        }
        mTypeAdapter.setNewData(mAssembleIndex.getAssembles());
        mTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i=0;i<mAssembleIndex.getAssembles().size();i++){
                     if (position==i){
                         mAssembleIndex.getAssembles().get(i).setCheck(true);
                     }else{
                         mAssembleIndex.getAssembles().get(i).setCheck(false);
                     }
                }
                mTypeAdapter.notifyDataSetChanged();
                //弹框显示
                TypeModule(mAssembleIndex.getAssembles().get(position).getAssembleItems(),mAssembleIndex.getAssembles().get(position).getTypeName(),mAssembleIndex.getCollageRecords().getRecords());
            }
        });

        if (mAssembleIndex.getCollageRecords().getTotal()==0){
            mView.getImgListNull().setVisibility(View.VISIBLE);
            mView.getAssembleMainList().setVisibility(View.GONE);
        }else{
            mView.getImgListNull().setVisibility(View.GONE);
            mView.getAssembleMainList().setVisibility(View.VISIBLE);
            //滚动列表实现方法
            Log.i(TAG,"refreshCount = "+refreshCount);
            if(refreshCount == 0){
                mView.getAssembleMainList().addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
                mView.getAssembleMainList().setLayoutManager(linearLayoutManager);
                //mView.getAssembleMainList().setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
                //mView.getAssembleMainList().setItemAnimator(new DefaultItemAnimator());// 设置Item默认动画，加也行，不加也行。
                refreshCount++;
            }
            mView.getAssembleMainList().setAdapter(mAutoPollAdapter=new AutoPollAdapter(mContext));
            //Log.i(TAG,"addData ==> getRecords = "+mAssembleIndex.getCollageRecords().getRecords());
            mAutoPollAdapter.addData(mAssembleIndex.getCollageRecords().getRecords());
            if (mAssembleIndex.getCollageRecords().getRecords().size()<=3){
                mView.getAssembleMainList().stop();
            }else{
                mView.getAssembleMainList().start();
            }
            mAutoPollAdapter.setOnItemClickListener(new AutoPollAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(String cdesk,String customerCode) {
                    if (AccountMgr.getCode(mContext).equals(customerCode)){
                        Toast.makeText(mContext,"亲，您只能加入他人的拼团哦！",Toast.LENGTH_SHORT).show();
                    }else{
                        for (int i=0;i<mAssembleIndex.getCollageRecords().getRecords().size();i++){
                            if (mAssembleIndex.getCollageRecords().getRecords().get(i).getCdesk().equals(cdesk)){
                                mAssre=mAssembleIndex.getCollageRecords().getRecords().get(i);
                            }
                        }
                        isFilter = false;
                        joinPersonner(cdesk,true,mAssre.getDistanceNumber());
                    }
                }

                @Override
                public void onItemDetailsClick(String cdesk, String customerCode) {//立即加入旁边区域
                    if (AccountMgr.getCode(mContext).equals(customerCode)){
                        Toast.makeText(mContext,"亲，您只能加入他人的拼团哦！",Toast.LENGTH_SHORT).show();
                    }else{
                        for (int i=0;i<mAssembleIndex.getCollageRecords().getRecords().size();i++){
                            if (mAssembleIndex.getCollageRecords().getRecords().get(i).getCdesk().equals(cdesk)){
                                mAssre=mAssembleIndex.getCollageRecords().getRecords().get(i);
                            }
                        }
                        isFilter = false;
                        joinPersonner(cdesk,false,mAssre.getDistanceNumber());
                    }
                }
            });
        }

        mView.getAssembleSsf().setHeaderView(createHeaderView());
        mView.getAssembleSsf().setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mView.getAssembleSsf().setRefreshing(false);
                        progressBar.setVisibility(View.GONE);
                        getinfo();
                    }
                }, 1000);
            }

            @Override
            public void onPullDistance(int distance) {
                // pull distance
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });

    }

    //初始化轮播
    public void initBanner() {
        //放图片地址的集合
        list_images_path = new ArrayList<>();
        if (mListAdvert.size()>0){
            for (int i = 0; i < mListAdvert.size(); i++) {
                list_images_path.add(mListAdvert.get(i).getImageUrl());
            }
        }else{
            //如果数据为空添加两张默认图
            list_images_path.add("https://kjb-oss.oss-cn-shenzhen.aliyuncs.com/ul9zg740a645wxjfxddl.png");
            list_images_path.add("https://kjb-oss.oss-cn-shenzhen.aliyuncs.com/h3xjask0xyj7bclwdzwv.png");
        }
        //设置banner样式
        mView.getBanner().setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mView.getBanner().setImageLoader(new GlideImageLoader());
        //设置图片集合
        mView.getBanner().setImages(list_images_path).setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int i) {
                if (mListAdvert.size()>0){
                    Intent intent = new Intent();
                    if (StateUtils.ADVERT_NATIVE.equals(mListAdvert.get(i).getPositionType())) { //转跳原生
                        if (!TextUtils.isEmpty(mListAdvert.get(i).getPositionUrl().toString())) {
                            if (!TextUtils.isEmpty(mListAdvert.get(i).getParameter())){
                                ParameterBean mBean = JSON.parseObject(mListAdvert.get(i).getParameter(), ParameterBean.class);
                                RouteManager.startActivity(mContext, mListAdvert.get(i).getPositionUrl(), mBean);
                            }else{
                                RouteManager.startActivity(mContext, mListAdvert.get(i).getPositionUrl(), new ParameterBean());
                            }
                        }
                    } else if (StateUtils.ADVERT_URL.equals(mListAdvert.get(i).getPositionType())) { //转跳到URL
                        /*Log.i(TAG,"mListAdvert = "+mListAdvert);
                        Log.i(TAG,"mListAdvert.get(i)) = "+mListAdvert.get(i));
                        Log.i(TAG,"mListAdvert.get(i).getPositionUrl() = "+mListAdvert.get(i).getPositionUrl());*/
                        if (null != mListAdvert.get(i).getPositionUrl() && !TextUtils.isEmpty(mListAdvert.get(i).getPositionUrl().toString())) {
                            intent.setClass(mContext, WebViewsActivity.class);
                            intent.putExtra("web_view_url", mListAdvert.get(i).getPositionUrl());
                            intent.putExtra("web_view_title", mListAdvert.get(i).getTitle());
                            mContext.startActivity(intent);
                        }
                    }
                    MobclickAgent.onEvent(mContext, "main_advertisement");

                }
            }
        });
        //设置banner动画效果
        mView.getBanner().setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        mView.getBanner().isAutoPlay(true);
        //设置轮播时间
        mView.getBanner().setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        mView.getBanner().setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        mView.getBanner().start();

    }


    public void onPresenterDestory(){
        if (mAutoPollAdapter!=null){
            mAutoPollAdapter.onAdapterDestroy();
        }
    }

    public void joinPersonner(final String cdesk,final boolean isDetails,final String distanceNumber) {
        Params params = new Params();
        params.add("cdesk", cdesk);
        mAuz.auzget(UrlPool.GET_JOIN_PERSONNER, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                //Log.i(TAG,"joinPersonner ==> data = "+data);
                List<AssemRecordsBean> mBean = JSON.parseArray(data, AssemRecordsBean.class);
                if (mBean.size() > 0 && isDetails) {
                    for (int i = 0; i < mBean.size(); i++) {
                        if(mBean.get(i).getNickname().equals(AccountMgr.getName(mContext))){
                            ToastUtils.showMyToast(Toast.makeText(mContext, "你已经加入该拼团了哦，在“我的拼单”可查询！.", Toast.LENGTH_SHORT), 1000);
                            return;
                        }
                    }
                }
                if(!isFilter){
                    JoinModle(mBean,cdesk,isDetails,distanceNumber);
                }else{
                    Toast toast = Toast.makeText(mContext, "已存在该商品拼单，已为您跳到加入拼团界面！", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    Intent intent=new Intent();
                    intent.setClass(mContext, ADetailsActivity.class);
                    intent.putExtra("assemble_details", mAssre); //AssemRecordsBean;
                    intent.putExtra("order_type", "join");
                    mContext.startActivity(intent);
                }

            }

            @Override
            public void AuzFailure(int errorCode, String msg) {

                Log.w("osh","data="+msg);
                mView.onFailure(errorCode, msg);
            }
        });
    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(mView.getAssembleSsf().getContext())
                .inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.down_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }


    public void TypeModule(List<AssembleItemsBean> listData,String title,List<AssemRecordsBean> listRecords){
        //PopAssemTypeModle
        if (listData.size()>0&&listData!=null){
            mMoble=new PopAssemTypeModle(mContext,title,listData,listRecords);
            mMoble.initAssemble(this);
            Popwindows popwindow = PopWindowUtil.getPopupWindow(mMoble.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                    .LayoutParams.MATCH_PARENT);
            mMoble.setPopwindow(popwindow);
            popwindow.show(mView.getBanner(), Popwindows.Location.BOTTOM);
        }else{
            Toast.makeText(mContext,"暂无相关拼团",Toast.LENGTH_SHORT).show();
        }
    }

    private List<String> mStrList=new ArrayList<>();
    private String StrTitle;
    private long mSeconds;
    public void JoinModle(List<AssemRecordsBean> mListAssem,String cdesk,boolean isDetails,String distanceNumber){

        if (isDetails){
            // AssemRecordsBean
            if (mStrList.size()>0){
                mStrList.clear();
            }
            int distanceNum = Integer.parseInt(distanceNumber);
            Log.i(TAG,"JoinModle ==> mListAssem.size = "+mListAssem.size()+" getRecords().size() = "+mAssembleIndex.getCollageRecords().getRecords().size()+" ");
            for (int  i=0;i<mAssembleIndex.getCollageRecords().getRecords().size();i++){
                if (cdesk.equals(mAssembleIndex.getCollageRecords().getRecords().get(i).getCdesk())){
                    StrTitle=mAssembleIndex.getCollageRecords().getRecords().get(i).getNickname();
                    for (int j=0;j< distanceNum;j++){
                        mStrList.add("data_null");
                    }
                    try{
                        SimpleDateFormat formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd HH:mm");
                        Date curDate =  new Date(System.currentTimeMillis());
                        Date endDate = formatter.parse(mAssembleIndex.getCollageRecords().getRecords().get(i).getSurplusTime());
                        mSeconds =endDate.getTime()-curDate.getTime();
                    }catch (Exception e){

                    }
                }
            }

            for (int k=0;k<mListAssem.size();k++){
                mStrList.add(k,mListAssem.get(k).getHeadImg());
            }


            PopAssembleJoin mJoin=new PopAssembleJoin(mContext,mStrList,cdesk,StrTitle,mSeconds,distanceNumber, new PopAssembleJoin.PopJoinListener() {
                @Override
                public void AssemJoin(String Orderid) {
                    for (int i=0;i<mAssembleIndex.getCollageRecords().getRecords().size();i++){
                        if (mAssembleIndex.getCollageRecords().getRecords().get(i).getCdesk().equals(Orderid)){
                            mAssre=mAssembleIndex.getCollageRecords().getRecords().get(i);
                        }
                    }
                    Intent intent=new Intent();
                    intent.setClass(mContext, ADetailsActivity.class);
                    intent.putExtra("assemble_details", mAssre); //AssemRecordsBean;
                    intent.putExtra("order_type", "join");
                    mContext.startActivity(intent);
                }
            });
            Popwindows popwindow = PopWindowUtil.getPopupWindow(mJoin.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                    .LayoutParams.MATCH_PARENT);
            mJoin.setPopwindow(popwindow);
            popwindow.show(mView.getBanner(), Popwindows.Location.BOTTOM);
        }else{
            for (int i=0;i<mAssembleIndex.getCollageRecords().getRecords().size();i++){
                if (mAssembleIndex.getCollageRecords().getRecords().get(i).getCdesk().equals(cdesk)){
                    mAssre=mAssembleIndex.getCollageRecords().getRecords().get(i);
                }
            }
            Intent intent=new Intent();
            intent.setClass(mContext, ADetailsActivity.class);
            intent.putExtra("assemble_details", mAssre); //AssemRecordsBean;
            intent.putExtra("order_type", "join");
            mContext.startActivity(intent);
        }
    }

    @Override
    public void filterExistAssemble(String productName, int position,String cdesk) {
        Log.i(TAG,"filterExistAssemble ==> productName = "+productName+" position = "+position);
        isFilter = true;
        for (int i=0;i<mAssembleIndex.getCollageRecords().getRecords().size();i++){
            if (mAssembleIndex.getCollageRecords().getRecords().get(i).getCdesk().equals(cdesk)){
                mAssre=mAssembleIndex.getCollageRecords().getRecords().get(i);
            }
        }
        joinPersonner(cdesk,true,mAssre.getDistanceNumber());

    }
}
